package com.song.email.core;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Vector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.song.email.bean.Auth;
import com.song.email.util.common.Config;
import com.song.email.util.common.Counter;
import com.thoughtworks.xstream.XStream;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class AuthCenter {
	private Log log = LogFactory.getLog(AuthCenter.class);
	private static AuthCenter authCenter = null;
	private Vector<Auth> authList = new Vector<Auth>();
	private int authIndex = 0;
	
	private AuthCenter(){}
	
	public synchronized static AuthCenter getInstance(){
		if(null == authCenter){
			authCenter = new AuthCenter();
		}
		return authCenter;
	}
	
	public void init(){
		XStream xstream = new XStream();  
        xstream.alias("auths", Vector.class);  
        xstream.alias("auth", Auth.class);  
        String filePath = AuthCenter.class.getResource("/"+Config.authFileName).getPath();
        BufferedReader bReader = null;
        try {
        	bReader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),Config.encoding));
			authList = (Vector)xstream.fromXML(bReader);
			if(authList != null){
				Counter.authCount = Counter.authCount + authList.size();
			}
		} catch (UnsupportedEncodingException e) {
			log.error("加载auths.xml时,中文编码输入错误.编码:" + Config.encoding,e);
		} catch (FileNotFoundException e) {
			log.error("加载auths.xml时,文件未找到.",e);
		}finally{
			if(null != bReader){
				try {
					bReader.close();
				} catch (IOException e) {
					log.error("加载auths.xml时,关闭流异常.",e);
				}
			}
		}
	}

	public synchronized Auth getAuth(){
		if(null == authList || authList.size() <= 0){
			return null;
		}
		if(authIndex >= authList.size()){
			authIndex = 0;
		}
		return authList.get(authIndex++);
	}
	
	public synchronized int getAuthListSize(){
		return authList.size();
	}
}
